const addHeadingZero = num => (num > 9 ? num.toString() : `0${num}`);

export const getDisplayTimeBySeconds = (seconds, timeFormat = 'auto') => {
    if (!Number.isFinite(seconds)) {
        return 0;
    }

    const min = Math.floor(seconds / 60);
    const minStr = addHeadingZero(min);
    const secStr = addHeadingZero(Math.floor(seconds % 60));
    const minStrForHour = addHeadingZero(Math.floor(min % 60));
    const hourStr = Math.floor(min / 60);

    const mmSs = `${minStr}:${secStr}`;
    const hhMmSs = `${hourStr}:${minStrForHour}:${secStr}`;

    if (timeFormat === 'auto') {
        if (seconds >= 3600) {
            return hhMmSs;
        }
        return mmSs;
    }

    if (timeFormat === 'mm:ss') {
        return mmSs;
    }

    if (timeFormat === 'hh:mm:ss') {
        return hhMmSs;
    }

    return 0;
};

export function throttle(func, limit) {
    let inThrottle = false;
    return arg => {
        if (!inThrottle) {
            func(arg);
            inThrottle = true;
            setTimeout(() => {
                inThrottle = false;
            }, limit);
        }
    };
}

export const getPosX = event => {
    if (event instanceof MouseEvent) {
        return event.clientX;
    }
    return event.touches[0].clientX;
};

export const getPosY = event => {
    if (event instanceof MouseEvent) {
        return event.clientY;
    }
    return event.touches[0].clientY;
};
